package com.learn.config;

import com.learn.pojo.Configuration;
import com.learn.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {
    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 对UserMapper.xml进行解析 将其中的每个Sql语句 封装成一个MappedStatement对象
     *
     * @param inputStream
     */
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String nameSpace = rootElement.attributeValue("namespace");
        List<Element> selectList = rootElement.selectNodes("select");
        for (Element element :
                selectList) {
            //id的值
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            //statementId
            String key = nameSpace + "." + id;
            //封装MappedStatement
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            //填充configuration
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
